<template>
  <div class="profile">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>个人中心</h1>
        <p>管理您的个人信息和账户设置</p>
      </div>

      <div class="profile-content">
        <!-- 个人信息卡片 -->
        <div class="profile-card">
          <div class="profile-header">
            <div class="avatar-section">
              <img :src="userInfo.avatar" :alt="userInfo.username" class="user-avatar" />
              <el-button size="small" @click="changeAvatar">更换头像</el-button>
            </div>
            <div class="user-basic-info">
              <h2>{{ userInfo.userName }}</h2>
              <p class="user-email">{{ userInfo.email }}</p>
              <p class="join-date">加入时间：{{ formatDate(userInfo.createTime) }}</p>
            </div>
          </div>
        </div>

        <!-- 个人信息表单 -->
        <div class="info-form-card">
          <h3>个人信息</h3>
          <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="userName">
                  <el-input v-model="userInfo.userName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userInfo.email" :disabled="!editMode"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="昵称" prop="name">
                  <el-input v-model="userInfo.name" :disabled="!editMode"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="userInfo.phone" :disabled="!editMode"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button v-if="!editMode" type="primary" @click="enableEdit">编辑信息</el-button>
              <template v-else>
                <el-button type="primary" @click="saveUserInfo" :loading="saving">保存</el-button>
                <el-button @click="cancelEdit">取消</el-button>
              </template>
            </el-form-item>
          </el-form>
        </div>

        <!-- 密码修改 -->
        <div class="password-card">
          <h3>修改密码</h3>
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
            <!-- <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
            </el-form-item> -->
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog title="更换头像" :visible.sync="avatarDialogVisible" width="500px" :close-on-click-modal="false">
      <div class="avatar-upload-container">
        <!-- 当前头像预览 -->
        <div class="current-avatar">
          <h4>当前头像</h4>
          <img :src="userInfo.avatar" alt="当前头像" class="preview-avatar" />
        </div>

        <!-- 新头像预览 -->
        <div class="new-avatar" v-if="newAvatarPreview">
          <h4>新头像预览</h4>
          <div class="avatar-preview-container">
            <img :src="newAvatarPreview" alt="新头像预览" class="preview-avatar" />
          </div>
        </div>

        <!-- 文件上传区域 -->
        <div class="upload-area">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :disabled="uploadingAvatar" accept="image/*">
            <div class="upload-content" :class="{ 'uploading': uploadingAvatar }">
              <i class="el-icon-plus" v-if="!uploadingAvatar"></i>
              <i class="el-icon-loading" v-if="uploadingAvatar"></i>
              <div class="upload-text">
                {{ uploadingAvatar ? '正在处理图片...' : '点击选择图片' }}
              </div>
              <div class="upload-tip" v-if="!uploadingAvatar">
                支持 JPG、PNG 格式，文件大小不超过 2MB
              </div>
            </div>
          </el-upload>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAvatarUpload" :disabled="uploadingAvatar">取消</el-button>
        <el-button type="primary" @click="confirmAvatarUpload" :loading="uploadingAvatar"
          :disabled="!newAvatarFile || uploadingAvatar">
          {{ uploadingAvatar ? '上传中...' : '确认更换' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { editUserList, uploadAvatar } from '@/api/user'
import { removeToken } from '@/utils/auth'

export default {
  name: 'Profile',
  computed: {
    ...mapGetters(['user']),
  },
  data() {
    return {
      editMode: false,
      saving: false,
      changingPassword: false,

      // 头像上传相关
      avatarDialogVisible: false,
      uploadingAvatar: false,
      newAvatarFile: null,
      newAvatarPreview: '',
      originalImageData: null,
      showCropControls: false,
      userInfo: {},

      originalUserInfo: {},

      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },

      stats: {
        totalApplications: 5,
        approvedApplications: 3,
        adoptedPets: 2,
        daysJoined: 225
      },

      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },

      passwordRules: {
        // currentPassword: [
        //   { required: true, message: '请输入当前密码', trigger: 'blur' }
        // ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    this.loadUserInfo()
  },

  methods: {
    loadUserInfo() {
      this.userInfo = { ...this.user }
    },

    enableEdit() {
      this.editMode = true
      this.originalUserInfo = { ...this.userInfo }
    },

    cancelEdit() {
      this.editMode = false
      this.userInfo = { ...this.originalUserInfo }
    },

    saveUserInfo() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.saving = true
          // 模拟API调用
          editUserList({
            id: this.userInfo.userId,
            name: this.userInfo.name,
            email: this.userInfo.email,
            phone: this.userInfo.phone
          }).then(res => {
            if (res.code === 200) {
              // 重新获取最新的用户数据
              this.$store.dispatch('user/updateProfile').then(() => {
                this.loadUserInfo() // 重新加载用户信息到本地
              })
              
              this.saving = false
              this.editMode = false
              this.$message.success('个人信息更新成功')
            }
          }).catch(error => {
            this.saving = false
            this.$message.error('更新失败，请重试')
          })
        }
      })
    },

    changeAvatar() {
      this.avatarDialogVisible = true
      this.newAvatarFile = null
      this.newAvatarPreview = ''
      this.originalImageData = null
      this.showCropControls = false
    },

    // 头像上传前的验证
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']

      if (!isImage || !validTypes.includes(file.type)) {
        this.$message.error('只能上传 JPG、PNG、GIF 格式的图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      // 显示处理状态
      this.uploadingAvatar = true
      // 创建预览
      this.createImagePreview(file)
      this.newAvatarFile = file

      // 阻止自动上传，等待用户确认
      return false
    },

    // 创建图片预览
    createImagePreview(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.originalImageData = e.target.result
        this.newAvatarPreview = e.target.result
        this.showCropControls = true

        // 自动压缩图片
        this.compressImage(e.target.result)
          .then(() => {
            this.uploadingAvatar = false
          })
          .catch(error => {
            this.uploadingAvatar = false
            this.$message.error('图片处理失败，请重新选择')
          })
      }
      reader.onerror = () => {
        this.uploadingAvatar = false
        this.$message.error('图片读取失败，请重新选择')
      }
      reader.readAsDataURL(file)
    },

    // 图片压缩功能
    compressImage(imageData, quality = 0.8, maxWidth = 400, maxHeight = 400) {
      return new Promise((resolve) => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()

        img.onload = () => {
          // 计算压缩后的尺寸
          let { width, height } = img

          if (width > height) {
            if (width > maxWidth) {
              height = (height * maxWidth) / width
              width = maxWidth
            }
          } else {
            if (height > maxHeight) {
              width = (width * maxHeight) / height
              height = maxHeight
            }
          }

          canvas.width = width
          canvas.height = height

          // 绘制压缩后的图片
          ctx.drawImage(img, 0, 0, width, height)

          // 转换为blob
          canvas.toBlob((blob) => {
            const reader = new FileReader()
            reader.onload = (e) => {
              this.newAvatarPreview = e.target.result
              resolve(e.target.result)
            }
            reader.readAsDataURL(blob)
          }, 'image/jpeg', quality)
        }

        img.src = imageData
      })
    },

    // 确认上传头像
    confirmAvatarUpload() {
      if (!this.newAvatarFile) {
        this.$message.error('请先选择图片')
        return
      }

      this.uploadingAvatar = true
      this.$message.info('正在上传头像，请稍候...')

      // 将base64转换为File对象
      this.dataURLtoFile(this.newAvatarPreview, this.newAvatarFile.name)
        .then(file => {
          // 调用上传API
          const formData = new FormData()
          formData.append('file', file)
          return uploadAvatar(formData)
        })
        .then(res => {
          if (res.code === 200) {
            // 更新用户头像URL
            editUserList({
              avatar: res.data,
              id: this.userInfo.userId
            }).then(res => {
              if (res.code === 200) {
                this.userInfo.avatar = res.data
              }
            })
            this.avatarDialogVisible = false
          } else {
            this.$message.error(res.message || '头像更新失败')
          }
        })
        .catch(error => {
          console.error('头像上传失败:', error)
        })
        .finally(() => {
          this.uploadingAvatar = false
        })
    },

    // 将base64转换为File对象
    dataURLtoFile(dataurl, filename) {
      return new Promise((resolve) => {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)

        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }

        const file = new File([u8arr], filename, { type: mime })
        resolve(file)
      })
    },

    // 取消头像上传
    cancelAvatarUpload() {
      this.avatarDialogVisible = false
      this.newAvatarFile = null
      this.newAvatarPreview = ''
      this.originalImageData = null
      this.showCropControls = false
    },

    changePassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.changingPassword = true
          // 模拟API调用
          editUserList({
            id: this.userInfo.userId,
            password: this.passwordForm.newPassword
          }).then(res => {
            if (res.code === 200) {
              this.changingPassword = false
              this.passwordForm = {
                currentPassword: '',
                newPassword: '',
                confirmPassword: ''
              }
              removeToken()
              this.$router.push('/login')
              this.$message.success('密码修改成功')
            }
          })
        }
      })
    },

    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },

    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.profile {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px 0;
}


.profile-content {
  display: grid;
  gap: 30px;
}

.profile-card,
.info-form-card,
.password-card,
.stats-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  gap: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 15px;
  border: 4px solid #f0f0f0;
}

.user-basic-info h2 {
  font-size: 24px;
  color: #333;
  margin-top: 30px;
}

.user-email {
  color: #666;
  font-size: 16px;
  margin-bottom: 5px;
}

.join-date {
  color: #999;
  font-size: 14px;
}

.info-form-card h3,
.password-card h3,
.stats-card h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 25px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

/* 头像上传对话框样式 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-avatar,
.new-avatar {
  text-align: center;
}

.current-avatar h4,
.new-avatar h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 16px;
}

.avatar-preview-container {
  position: relative;
  display: inline-block;
}

.preview-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f0f0;
}

.upload-area {
  margin-top: 20px;
}

.avatar-uploader {
  display: block;
  width: 100%;
}

.upload-content {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-content:hover {
  border-color: #409eff;
}

.upload-content.uploading {
  border-color: #409eff;
  background-color: #f0f9ff;
  cursor: not-allowed;
}

.upload-content .el-icon-plus,
.upload-content .el-icon-loading {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-content .el-icon-loading {
  color: #409eff;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.upload-text {
  color: #606266;
  font-size: 16px;
  margin-bottom: 5px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>